<template>
  <div id="userManageView">
    <a-card class="search-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-search />
          <span>搜索用户</span>
        </div>
      </template>
      <a-form
        :model="searchParams"
        layout="grid"
        :grid-props="{ cols: 3, gutter: 16 }"
      >
        <a-form-item field="id" label="用户编号" tooltip="请输入用户的编号">
          <a-input
            v-model="searchParams.id"
            placeholder="请输入用户编号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="userName" label="用户名称" tooltip="请输入用户名称">
          <a-input
            v-model="searchParams.userName"
            placeholder="请输入用户名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" status="normal" @click="doSubmit">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 用户列表表格 -->
    <a-card class="table-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-user-group />
          <span>用户列表</span>
        </div>
      </template>
      <a-table
        row-key="id"
        :loading="loading"
        :column-resizable="true"
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
          showJumper: true,
          showPageSize: true,
        }"
        @page-change="onPageChange"
        @pageSizeChange="onPageSizeChange"
        :stripe="true"
      >
        <template #userAvatar="{ record }">
          <a-avatar :size="54" shape="circle">
            <img alt="userAvatar" :src="record.userAvatar" />
          </a-avatar>
        </template>
        <template #userRole="{ record }">
          <a-tag v-if="record.userRole === 'user'" color="blue">普通用户</a-tag>
          <a-tag v-if="record.userRole === 'admin'" color="green">管理员</a-tag>
        </template>
        <template #userProfile="{ record }">
          <a-tooltip :content="record.userProfile || '暂无简介'">
            <span class="profile-text">{{
              record.userProfile || "暂无简介"
            }}</span>
          </a-tooltip>
        </template>
        <template #createTime="{ record }">
          {{ moment(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #updateTime="{ record }">
          {{ moment(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #optional="{ record }">
          <a-space>
            <a-button
              type="text"
              size="small"
              @click="openModalForm(record.id)"
            >
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除此用户吗?"
              type="warning"
              okText="确定"
              cancelText="取消"
              position="top"
              @ok="doDelete(record)"
            >
              <a-button type="text" status="danger" size="small">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
        <template #empty>
          <div class="empty-state">
            <icon-info :size="64" />
            <p>暂无用户数据</p>
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 用户编辑弹窗 -->
    <a-modal
      width="500px"
      :visible="visible"
      :title="modalTitle"
      @ok="handleOk"
      @cancel="closeModel"
      unmountOnClose
    >
      <!-- 显示头像（不可编辑） -->
      <div class="avatar-display-container">
        <a-avatar :size="90" shape="circle">
          <img alt="头像" :src="userInfo?.userAvatar" />
        </a-avatar>
      </div>
      <a-form
        :model="userInfo"
        ref="userForm"
        label-align="right"
        style="max-width: 100%; margin: 24px auto 0"
        :auto-label-width="true"
      >
        <a-form-item field="userName" label="用户名称" required>
          <a-input v-model="userInfo.userName" placeholder="请输入用户名称" />
        </a-form-item>
        <a-form-item field="userAccount" label="账号" required>
          <a-input v-model="userInfo.userAccount" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item field="userRole" label="用户角色" required>
          <a-select v-model="userInfo.userRole" placeholder="请选择用户角色">
            <a-option value="admin">管理员</a-option>
            <a-option value="user">普通用户</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="userProfile" label="用户简介">
          <a-textarea v-model="userInfo.userProfile" placeholder="请输入简介" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="closeModel">取消</a-button>
          <a-button type="primary" @click="handleOk" :loading="submitting"
            >确定</a-button
          >
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, watchEffect } from "vue";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import { useRouter } from "vue-router";
import { User, UserControllerService } from "../../../generated";
import {
  IconUserGroup,
  IconHome,
  IconSearch,
  IconRefresh,
  IconEdit,
  IconDelete,
  IconPlus,
  IconInfo,
} from "@arco-design/web-vue/es/icon";

const router = useRouter();
const tableRef = ref();
const userForm = ref();

const visible = ref(false);
const submitting = ref(false);
const loading = ref(false);
const modalTitle = ref("编辑用户");
const userInfo = ref<User>({} as User);

const dataList = ref([]);
const total = ref(0);
const searchParams = ref({
  id: undefined,
  userName: "",
  email: "",
  phone: "",
  pageSize: 10,
  current: 1,
});

/**
 * 加载用户数据
 */
const loadData = async () => {
  loading.value = true;
  try {
    const res = await UserControllerService.listUserByPageUsingPost({
      ...searchParams.value,
      sortField: "createTime",
      sortOrder: "descend",
    });
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      message.error("加载失败：" + res.message);
    }
  } catch (error) {
    message.error("请求出错：" + error);
  } finally {
    loading.value = false;
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

/**
 * 表格列定义
 */
const columns = [
  {
    title: "编号",
    dataIndex: "id",
    align: "center",
    width: 250,
  },
  {
    title: "头像",
    slotName: "userAvatar",
    align: "center",
    width: 80,
  },
  {
    title: "账号",
    dataIndex: "userAccount",
    align: "center",
    width: 120,
  },
  {
    title: "名称",
    dataIndex: "userName",
    align: "center",
    width: 120,
  },
  {
    title: "简介",
    slotName: "userProfile",
    align: "center",
    ellipsis: true,
  },
  {
    title: "角色",
    slotName: "userRole",
    align: "center",
    width: 100,
  },
  {
    title: "更新时间",
    slotName: "updateTime",
    align: "center",
    width: 250,
  },
  {
    title: "操作",
    slotName: "optional",
    align: "center",
    width: 160,
    fixed: "right",
  },
];

/**
 * 分页-页码变化
 * @param page
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 分页-每页条数变化
 * @param size
 */
const onPageSizeChange = (size: number) => {
  searchParams.value = {
    ...searchParams.value,
    pageSize: size,
  };
};

/**
 * 重置搜索条件
 */
const resetSearch = () => {
  searchParams.value = {
    id: undefined,
    userName: "",
    email: "",
    phone: "",
    pageSize: 10,
    current: 1,
  };
};

/**
 * 添加用户按钮点击
 */
const addUser = () => {
  modalTitle.value = "添加用户";
  userInfo.value = {
    userAvatar: "https://api.dicebear.com/7.x/miniavs/svg",
    userRole: "user",
  } as User;
  visible.value = true;
};

/**
 * 打开编辑用户弹窗
 */
const openModalForm = async (userId: any) => {
  modalTitle.value = "编辑用户";
  try {
    const res = await UserControllerService.getUserByIdUsingGet(userId);
    if (res.code === 0 && res.data) {
      userInfo.value = res.data;
    } else {
      message.error("获取用户信息失败：" + res.message);
      return;
    }
  } catch (error) {
    message.error("请求出错：" + error);
    return;
  }
  visible.value = true;
};

/**
 * 删除用户
 */
const doDelete = async (user: User) => {
  try {
    const res = await UserControllerService.deleteUserUsingPost({
      id: user.id,
    });
    if (res.code === 0) {
      message.success("删除成功");
      loadData();
    } else {
      message.error("删除失败：" + res.message);
    }
  } catch (error) {
    message.error("请求出错：" + error);
  }
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

/**
 * 确定编辑按钮
 */
const handleOk = async () => {
  submitting.value = true;
  try {
    let res;
    // 根据模态框标题判断是添加还是编辑操作
    if (modalTitle.value === "添加用户") {
      // 添加用户
      res = await UserControllerService.addUserUsingPost({
        ...userInfo.value,
      });
    } else {
      // 编辑用户
      res = await UserControllerService.updateUserUsingPost({
        ...userInfo.value,
      });
    }

    if (res.code === 0) {
      message.success("操作成功");
      visible.value = false;
      loadData();
    } else {
      message.error("操作失败：" + res.message);
    }
  } catch (error) {
    message.error("请求出错：" + error);
  } finally {
    submitting.value = false;
  }
};

/**
 * 关闭弹窗
 */
const closeModel = () => {
  visible.value = false;
};
</script>

<style scoped>
#userManageView {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #165dff;
  font-weight: 500;
}

/* 卡片样式 */
.search-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 表格操作区域 */
.table-operations {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 简介文本溢出处理 */
.profile-text {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 头像显示 */
.avatar-display-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #86909c;
}

.empty-state p {
  margin-top: 12px;
  font-size: 14px;
}

/* 列表中的按钮样式 */
:deep(.arco-btn-text) {
  padding: 0 8px;
}

/* 表格样式优化 */
:deep(.arco-table-th) {
  background-color: #f2f3f5;
  font-weight: 600;
}

:deep(.arco-table-tr:nth-child(even)) {
  background-color: #f9fafb;
}

:deep(.arco-table-td) {
  padding: 12px 16px;
}
</style>
